package com.hwg.shiliupro.webSocket;

import cn.hutool.json.JSONUtil;
import com.hwg.shiliupro.po.MsgInfo;
import com.hwg.shiliupro.po.SessionList;
import com.hwg.shiliupro.po.User;
import com.hwg.shiliupro.service.MsgInfoService;
import com.hwg.shiliupro.service.SessionListService;
import com.hwg.shiliupro.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/websocket/{userId}/{sessionId}")
public class WebSocket {
    //key: userId    value:webSocket
    public static Map<Integer,WebSocket> webSockets = new ConcurrentHashMap<>();
    //key:userId     value:list  而list存储sessionId和session
    public static Map<Integer,List<Object>> sessionPool =new ConcurrentHashMap<>();
    //当前已登录用户  key:userName  value:user对象
    public static Map<String, User> loginUserPool = new ConcurrentHashMap<>();

    @Autowired
    private SessionListService sessionListService;

    @Autowired
    private MsgInfoService msgInfoService;

    @Autowired
    private UserService userService;

    private Session session;

    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")Integer userId, @PathParam(value="sessionId")String sessionId) {
        System.out.println("连接成功~");
        this.session = session;
        webSockets.put(userId,this);
        List<Object> list = new ArrayList<>();
        list.add(sessionId);
        list.add(session);
        sessionPool.put(userId,list);
        log.info("有新用户加入,当前在线人数为:{}",webSockets.size());
    }

    @OnClose
    public void onClose(Session session, @PathParam(value="userId")Integer userId, @PathParam(value="sessionId")String sessionId){
        //断开连接 删除用户删除session
//        sessionPool.remove(userId);
//        webSockets.remove(userId);
//        User user =  userService.selectById(userId);
//        loginUserPool.remove(user.getName());
//        log.info("有用户退出,当前在线人数为:{}",webSockets.size());
    }

    @OnMessage
    public void onMessage(String message,Session session, @PathParam(value="userId")Integer userId, @PathParam(value="sessionId")String sessionId){
        log.info("收到客户端消息：{}",message);
        SessionList sessionList = sessionListService.selectById(Integer.parseInt(sessionId));
        User user = userService.selectById(userId);
        //封装MsgInfo实体 消息持久化到数据库
        MsgInfo msgInfo = new MsgInfo();
        msgInfo.setContent(message);
        msgInfo.setCreateTime(new Date());
        msgInfo.setFromUserId(userId);
        msgInfo.setFromUserName(user.getName());
        msgInfo.setToUserId(sessionList.getToUserId());
        msgInfo.setToUserName(sessionList.getListName());
        msgInfo.setUnReadFlag(0);
        msgInfoService.insert(msgInfo);
        //分情况  接收者 不在线/未点击(发送者的消息)
        List<Object> list = sessionPool.get(sessionList.getToUserId());
        if(list == null || list.isEmpty()){
            //接收者 不存在       /未点击(发送者的消息),更新未读数
            sessionListService.addUnReadCount(sessionList.getUserId(),sessionList.getToUserId());
        }else{
            //接收者存在 判断会话是否存在  sessionList的id      这里是不是写反了
            String id = sessionListService.selectByUserIdAndToUserId(sessionList.getUserId(),sessionList.getToUserId())+"";
            String o = list.get(0) + "";
            if(id.equals(o)){
                //会话存在，直接发送消息
                sendTextMessage(sessionList.getToUserId(), JSONUtil.toJsonStr(msgInfo));
            }else{
                //判断会话列表是否存在
                if(id == null || "".equals(id) || "null".equals(id)){
                    //新增会话列表
                    SessionList newList = new SessionList();
                    newList.setUserId(sessionList.getUserId());
                    newList.setToUserId(sessionList.getToUserId());
                    newList.setListName(user.getName());
                    newList.setUnReadCount(1);
                    sessionListService.insert(newList);
                }else{
                    // 会话列表存在，更新未读消息数量
                    sessionListService.addUnReadCount(sessionList.getUserId(),sessionList.getToUserId());
                }
                //会话不存在 发送列表消息
                List<SessionList> sessionLists = sessionListService.selectByUserId(sessionList.getToUserId());
                sendTextMessage(sessionList.getToUserId(),JSONUtil.toJsonStr(sessionLists));
            }
        }
    }

    public void sendTextMessage(Integer toUserId, String message) {
        // list的1号位存放的是session
        Session session = (Session) sessionPool.get(toUserId).get(1);
        if(session != null){
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
